package com.woniuxy.death.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 邓宇昂
 * @Description: 死信队列配置
 * @DateTime: 22/12/29/0029 17:27
 * @Component: 成都蜗牛学苑
 **/
@Configuration
public class DeathConfig {
    // =============== 正常队列 交换机 ==============
    private Map<String, Object> bindingDeathExchange() {
        Map<String, Object> args = new HashMap<>();
        //根据15672可视化里面，找到的key，value就是死信交换机的名字deathEx
        args.put("x-dead-letter-exchange","deathEx");
        args.put("x-dead-letter-routing-key","");//广播模式的死信交换机，所以不需要routingKey
        return args;
    }

    /**
     * 存放有过期时间消息的队列
     * ChangeLog : 1. 创建 (22/12/29/0029 17:28 [马宇航]);
     *
     * @return org.springframework.amqp.core.Queue
     */
    @Bean
    public Queue ttlQueue(){
        //两个正常队列，绑定到同一个死信交换机上
        Map<String,Object> args = bindingDeathExchange();
        args.put("x-message-ttl",10*1000);//消息在队列中存活10s后，就过期，成为死信。
        return new Queue("ttlQueue",true,false,false,args);
    }


    //有长度限制的队列
    @Bean
    public Queue lengthLimitQueue(){
        //两个正常队列，绑定到同一个死信交换机上
        Map<String,Object> args = bindingDeathExchange();
        args.put("x-max-length",5);//这个队列最大长度只有5个
        return new Queue("lengthLimitQueue",true,false,false,args);
    }
    @Bean
    public DirectExchange ordinaryExchange(){
        return new DirectExchange("normalEx",true,false);
    }
    @Bean
    public Binding ttlQueueBinding(){
        return BindingBuilder.bind(ttlQueue()).to(ordinaryExchange()).with("routingKey1");
    }
    @Bean
    public Binding lengthLimitQueueBinding(){
        return BindingBuilder.bind(lengthLimitQueue()).to(ordinaryExchange()).with("routingKey2");
    }
    // =============== 正常队列 交换机 ==============
    // =============== 死信队列 交换机 ==============
    @Bean
    public FanoutExchange deathEX(){
        return new FanoutExchange("deathEx",true,false);
    }
    @Bean
    public Queue deathQueue(){
        return new Queue("deathQueue");
    }
    @Bean
    public Binding deathBinding(){
        return BindingBuilder.bind(deathQueue()).to(deathEX());
    }
    // =============== 死信队列 交换机 ==============
}
